import React from "react";
import { Tree } from "antd";
import "./index.less";
export interface TreeTransferProps {
  onRight: (arr: any[]) => any;
  dataSource: any[];
  defaultValue?: any;
}

export interface TreeTransferState {}

class TreeTransfer extends React.Component<
  TreeTransferProps,
  TreeTransferState
> {
  // state = { :  }

  private treeLeftData: any[] = []; //树型结构完整菜单
  private dataList: any[] = []; //平面结构完整菜单
  private leftAllCheck: string[] = []; //左侧当前选中的元素及其祖先元素
  private leftCheck: string[] = []; //左侧当前选中的元素
  render() {
    return (
      <>
        <div className="transfer">
          <div className="transfer-list" style={{ width: "100%", height: 300 }}>
            <div className="transfer-list-header">
              <span className="transfer-list-header-title">菜单列表</span>
            </div>
            <div className="transfer-list-body">
              <div className="transfer-list-content">
                <Tree
                  checkable
                  defaultExpandAll={true}
                  treeData={this.treeLeftData}
                  onCheck={(checkedKeys: any, info: any) => {
                    this.onLeftCheck(checkedKeys, info);
                  }}
                  checkedKeys={this.leftCheck}
                ></Tree>
              </div>
            </div>
          </div>
        </div>
      </>
    );
  }

  //钩子函数
  componentWillMount() {
    // this.getMenuList();
    this.init();
  }
  shouldComponentUpdate(newProps, newState) {
    if (newProps.defaultValue) {
      this.leftCheck = newProps.defaultValue.sub;
      this.leftAllCheck = newProps.defaultValue.all;
      newProps.onRight(newProps.defaultValue.sub);
    }
    return true;
  }
  init() {
    this.dataList = this.props.dataSource; //菜单平面数据
    this.treeLeftData = this.listToTree(this.props.dataSource); //菜单树状数据
    this.forceUpdate();
  }
  getKeyInList(arr: any) {
    let array: any[] = [];
    let { dataList } = this;
    arr.map((item) => {
      for (let i = 0; i < dataList.length; i++) {
        if (dataList[i].key === item) {
          array.push(dataList[i]);
        }
      }
      return item;
    });
    return array;
  }

  onLeftCheck = (checkedKeys: string[], info: any) => {
    this.leftCheck = checkedKeys;
    this.leftAllCheck = checkedKeys.concat(info.halfCheckedKeys);
    this.props.onRight(this.leftAllCheck);
    this.forceUpdate();
  };
  /**重新组成树结构。 */
  listToTree = (list: any) => {
    if (!Array.isArray(list) || list.length === 0) return list;
    let map: any = {},
      roots: any = [];
    for (let i = 0; i < list.length; i++) {
      map[list[i].key] = i;
      list[i].children = [];
    }
    for (let i = 0; i < list.length; i++) {
      let node = list[i];
      if (node.parentkey === null) {
        roots.push(node);
      } else {
        list[map[node.parentkey]].children.push(node);
      }
    }
    return roots;
  };
}

export default TreeTransfer;
